from models.basemodel import BaseModel
from models.character import Character
from models.idiom import Idiom
from models.word import Word

import json,os
cur_dir=os.path.dirname(__file__)
data_dir=os.path.join(os.path.dirname(cur_dir),'data')
def seed_table(records:list[dict],model:BaseModel,erase_old=True):
    if erase_old:
        model.drop_table()
    model.create_table()
    for rec in records:
        model.create(**rec)

def open_file(file_name):
    file_path=os.path.join(data_dir,file_name)
    return open(file_path,encoding='utf8')

def seed_characters():


    file_path=os.path.join(data_dir,'word.json')
    with open(file_path,encoding='utf8') as f:
        records=json.load(f)
        def format(recs):
            for r in recs:
                del r['oldword']
                r['literal']=r['word']
                del r['word']
                r['more_info']=r['more']
                del r['more']
                r['radical']=r['radicals']
                del r['radicals']
                yield r
        seed_table(format(records),Character)

def seed_words():
    f=open_file('ci.json')
    records=json.load(f)
    def format(recs):
        for r in recs:
            r['literal']=r['ci']
            del r['ci']
            yield r
    seed_table(format(records),Word)

def seed_idiom():
    file=open_file('idiom.json')
    records=json.load(file)
    def format(recs):
        for r in recs:
            r['literal']=r['word']
            del r['word']
            yield r
    seed_table(format(records),Idiom)